const defaultMapConfig: {
  zoom?: number
  center?: number[]
  viewMode?: string
  pitch?: number
  mapStyle?: string
} = {
  zoom: 16, // 级别
  center: [120.209741, 30.246767], // 中心点坐标，杭州萧山分局[120.272037, 30.13913]
  viewMode: '2D', // 使用3D视图 要和pitch:75（地图俯仰角度，有效范围 0 度- 83 度）配合使用
  pitch: 55,
  mapStyle: 'amap://styles/e1524ca2d6b1244f44e97b21d04d60bc', // 设置地图的显示样式
}
let map: any = null
// 渲染地图
export const readerMap = (id: string) => {
  map = new AMap.Map(id, defaultMapConfig)
  return map
}
interface IAddMarker {
  lngLat: (number | string)[]
  extData?: unknown
  imgSrc?: unknown
  imgSize?: number[]
}
// { lngLat, extData, imgSrc, imgSize = [40, 40] }
// 添加坐标点
export const addMarker = (
  params: IAddMarker,
  callback?: (extData: unknown, evt: any) => void
) => {
  if (!params.imgSize) {
    params.imgSize = [40, 40]
  }

  let icon = null
  if (params.imgSrc) {
    icon = new AMap.Icon({
      size: new AMap.Size(...params.imgSize),
      image: params.imgSrc || '',
      imageSize: new AMap.Size(...params.imgSize),
    })
  }
  let marker = new AMap.Marker({
    position: new AMap.LngLat(params.lngLat[0], params.lngLat[1]),
    icon,
    extData: params.extData,
  })
  marker.on('click', (evt: any) => {
    let extData = evt.target.getExtData()
    if (callback) callback(extData, evt)
  })
  return marker
}
// 实例
// const createInfoWindow = () => {
//   const win = document.createElement('div')
//   win.className = 'test'
//   win.innerHTML = '测试'
//   return win
// }
export const addInfoWindow = (position: (number | string)[], content: HTMLElement) => {
  let infoWindow = new AMap.InfoWindow({
    isCustom: true,
    content: content,
    offset: new AMap.Pixel(0, -30),
  })
  infoWindow.open(map, position)
}
// 获取当前位置
export const currentLocation = (callback: (position: []) => void) => {
  AMap.plugin('AMap.Geolocation', function () {
    var geolocation = new AMap.Geolocation({
      enableHighAccuracy: true, //是否使用高精度定位，默认:true
      timeout: 10000, //超过10秒后停止定位，默认：5s
      position: 'RB', //定位按钮的停靠位置
      offset: [10, 20], //定位按钮与设置的停靠位置的偏移量，默认：[10, 20]
      zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
    })
    map.addControl(geolocation)
    geolocation.getCurrentPosition((status: string, result: any) => {
      if (status == 'complete') {
        map.setCenter(result.position)
        const position = result.position.toString().split(',')
        callback(position)
      } else {
        console.error('定位失败')
      }
    })
  })
}
// 点击地图触发
export const handleMap = (callback: (ev: any) => void) => {
  map.on('click', (ev: any) => {
    // 清楚所有信息框
    //   map.clearInfoWindow()
    // 触发事件的对象
    // let target = ev.target
    // 触发事件的地理坐标，AMap.LngLat 类型
    //   let lnglat = ev.lnglat
    // 触发事件的像素坐标，AMap.Pixel 类型
    //   let pixel = ev.pixel
    // 触发事件类型
    //   let type = ev.type
    if (callback) callback(ev)
  })
}
